<template>
    <span class="timer-com">
        <span class="timer">
            <img src="@/assets/ic_time.png" alt="" />
        </span>
        <label class="time-text">{{ formatTime(timer.duration) }}</label>
    </span>
</template>

<script setup>
import { examTimer } from '@/stores/timer.js'

const timer = examTimer()

let timerId

function formatTime(seconds) {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const remainingSeconds = seconds % 60
    return `${hours < 10 ? '0' : ''}${hours}:${minutes < 10 ? '0' : ''}${minutes}:${
        remainingSeconds < 10 ? '0' : ''
    }${remainingSeconds}`
}

// 开始计时
const startTime = () => {
    if (timerId) return
    timerId = setInterval(() => {
        timer.addTime()
    }, 1000)
}

// 停止计时
const stopTime = () => {
    clearInterval(timerId)
    timerId = null
}

// 初始化时间
const initTime = (second) => {
    timer.initTIme(second)
}

// 获取当前时间
const getTime = () => {
    return timer.duration
}

defineExpose({
    startTime,
    initTime,
    stopTime,
    getTime
})
</script>

<style scoped>
.timer-com {
    display: flex;
    align-items: center;
}
.timer {
    width: 14px;
    height: 14px;
    line-height: 14px;
}
.timer > img {
    width: 100%;
    height: 100%;
}
.time-text {
    width: 64px;
    text-align: right;
}
</style>
